package work;
import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FinalClient implements Runnable {
    DatagramSocket socket;
    byte[] buffer = new byte[8192];
    InetAddress serverAddress;
    int serverPort;

    // 日志文件
    File sendLogFile = new File("Client_out_log.txt");
    File receiveLogFile = new File("Client_in_log.txt");

    FinalClient(String serverIP, int serverPort) throws IOException {
        this.serverAddress = InetAddress.getByName(serverIP);
        this.serverPort = serverPort;
        socket = new DatagramSocket(1234); // 客户端监听 1234 端口
        new Thread(this).start(); // 启动接收线程
        System.out.println("客户端已启动，等待消息...");

        // 在启动时发送一条初始化消息，便于服务器记录客户端信息
        sendMessage("客户端已连接！");
    }

    // 接收服务器发送的消息
    @Override
    public void run() {
        while (true) {
            try {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet); // 接收消息

                String receivedMessage = new String(packet.getData(), 0, packet.getLength());
                System.out.println("【提示】收到数据来自：" + packet.getAddress() + "，端口：" + packet.getPort());
                System.out.println("【提示】收到的消息是：" + receivedMessage);

                // 写入接收日志
                logMessage(receiveLogFile, "接收", packet.getAddress(), receivedMessage);

                // 如果收到 "exit"，关闭接收线程
                if (receivedMessage.trim().equalsIgnoreCase("exit")) {
                    System.out.println("【提示】服务器已关闭连接，接收线程关闭...");
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close(); // 关闭客户端端口
        System.out.println("【提示】客户端接收线程已关闭。");
    }

    // 发送数据到服务器
    public void sendMessage(String message) {
        if (!message.isEmpty()) {
            try {
                DatagramPacket packet = new DatagramPacket(
                        message.getBytes(),
                        message.length(),
                        serverAddress,
                        serverPort);
                socket.send(packet);

                System.out.println("【提示】消息发送成功：" + message);
                // 写入发送日志
                logMessage(sendLogFile, "发送", serverAddress, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("【警告】消息为空，未发送！");
        }
    }

    // 写入日志的方法
    private void logMessage(File logFile, String action, InetAddress address, String message) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(logFile, true))) {
            String timestamp = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").format(new Date());
            writer.printf("%s: %s 时间: %s 内容: %s%n", action, address, timestamp, message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

        // 获取服务器的 IP 地址和端口
        System.out.println("请输入服务器的 IP 地址：");
        String serverIP = console.readLine();
        System.out.println("请输入服务器的端口号：");
        int serverPort = Integer.parseInt(console.readLine());

        FinalClient client = new FinalClient(serverIP, serverPort);

        while (true) {
            System.out.print("输入要发送的消息（输入 'exit' 退出）：");
            String message = console.readLine();

            // 如果输入 "exit"，退出程序
            if (message.trim().equalsIgnoreCase("exit")) {
                System.out.println("【提示】客户端退出发送循环...");
                client.sendMessage("客户端已断开连接");
                break;
            }

            client.sendMessage(message);
        }
        client.socket.close(); // 关闭客户端端口
        System.out.println("【提示】客户端已关闭。");
    }
}